package com.UdpRecieve.tool;


import java.io.*;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/*zip压缩解压*/
public class FileZip {


    /**
     * zip文件压缩
     * @param inputFile 待压缩文件夹/文件名
     * @param outputFile 生成的压缩包名字
     */

    public static void ZipCompress(String inputFile, String outputFile) throws Exception {
        //创建zip输出流
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
        //创建缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(out);
        File input = new File(inputFile);
        compress(out, bos, input,null);
        bos.close();
        out.close();
    }
    /**
     * 递归压缩
     * @param name 压缩文件名，可以写为null保持默认
     */
    public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException {
        if (name == null) {
            name = input.getName();
        }
        //如果路径为目录（文件夹）
        if (input.isDirectory()) {
            //取出文件夹中的文件（或子文件夹）
            File[] flist = input.listFiles();

            if (flist.length == 0)//如果文件夹为空，则只需在目的地zip文件中写入一个目录进入
            {
                out.putNextEntry(new ZipEntry(name + "/"));
            } else//如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, bos, flist[i], name + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
        {
            out.putNextEntry(new ZipEntry(name));
            FileInputStream fos = new FileInputStream(input);
            BufferedInputStream bis = new BufferedInputStream(fos);
            int len;
            //将源文件写入到zip文件中
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf,0,len);
            }
            bis.close();
            fos.close();
        }
    }


    /**
     * zip文件解压
     *
     * @param inputFile   待解压文件夹/文件
     * @param destDirPath 解压路径
     */
    public static void zipUncompress(String inputFile, String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile), Charset.forName("gbk"));
        ZipEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(destDirPath, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                //System.out.println(file.getName()+"的文件路径:"+file.getParent());
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                bos.close();
                out.close();
            }
        }
        zIn.close();
    }


    /**
     * zip文件解压
     * 返回文件总数
     * @param inputFile   待解压文件夹/文件
     * @param destDirPath 解压路径
     */
    public static int zipUncompressAndGetCount(String inputFile, String destDirPath) throws Exception {
        int fileCount = 0;
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile), Charset.forName("gbk"));
        ZipEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                fileCount++;
                file = new File(destDirPath+File.separator, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                System.out.println(file.getName()+"的文件路径:"+file.getParent());
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                bos.close();
                out.close();
            }
        }
        zIn.close();
        return fileCount;
    }


    /**
     * 获取zip包文件个数
     * 返回文件总数
     * @param inputFile   压缩包文件全路径
     */
    public static int getZipFileCount(String inputFile) throws Exception {
        int fileCount = 0;
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile), Charset.forName("gbk"));
        ZipEntry entry = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                fileCount++;
            }
        }
        zIn.close();
        return fileCount;
    }




    /**
     * zip文件解压(针对618)
     *
     * @param fileName   待解压文件名
     * @param filePath   待解压文件夹
     * @param destDirPath 解压路径
     */
    public static void zipUncompressSpecial(String fileName,String filePath, String destDirPath) throws Exception {
        File srcFile = new File(filePath+File.separator+fileName);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile), Charset.forName("gbk"));
        ZipInputStream zIn02 = new ZipInputStream(new FileInputStream(srcFile), Charset.forName("gbk"));
        ZipEntry entry = null;
        File file = null;
        int count = 0;
        while ((entry = zIn.getNextEntry())!=null){
            count++;
        }
        System.out.println(count);
        entry = null;
        String fileOutPutPath = destDirPath+File.separator+fileName.split("\\.")[0]+"_"+"unzip"+"_"+count;
        File fileOutPutPathC = new File(fileOutPutPath);
        if (!fileOutPutPathC.exists()){
            fileOutPutPathC.mkdirs();
        }
        while ((entry = zIn02.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(fileOutPutPath, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn02.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                bos.close();
                out.close();
            }
        }
    }

    public static void main(String[] args) {

        File f = new File("C:\\Users\\Administrator\\Desktop\\测试压缩包.zip");
        System.out.println(f.getParent());

        /*try {
            System.out.println(MD5FileUtils.getMD5(new File("C:\\Users\\Administrator\\Desktop\\曙光服务器.txt")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        /*压缩*/
        /*try {
            ZipCompress("D:\\Test", "D:\\TestbyYTT.zip");
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        /*解压*/
        try {
            zipUncompress("C:\\Users\\Administrator\\Desktop\\审批系统测试文件.zip", "D:\\测试\\测试压缩包");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        /*移动*/
        /*try {
            Files.move(Paths.get("C:\\Users\\Administrator\\Desktop\\测试压缩包.zip"),Paths.get("C:\\Users\\Administrator\\Desktop\\123\\测试压缩包.zip"), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }


}
